﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.DigitalOutput;
using MINERP.MODEL.DigitalModel;
using System.Collections;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;
using System.Threading;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MINERP.ComControls;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using MINERP.ComControls.Extension;

namespace MINERP.DigitalOutput
{
    public partial class FrmDigitalMain2 : FrmParent
    {
        //公共参数
        BLL.DigitalOutput.DigitalOutputBLL DBLL = new MINERP.BLL.DigitalOutput.DigitalOutputBLL();
        BLL.Common.WorkFlowListBLL WBLL = new MINERP.BLL.Common.WorkFlowListBLL();
        DataTable photoDT;          //照片信息集合
        DataTable filterPhotoDT;    //筛选后的照片信息集合
        int CurrentTechId;          //当前节点的Id
        bool CurrentPhotoMode;      //false分配打印机，true改变打印机
        BLL.DigitalOutput.DigitalOutputBLL.STPrinter currentPrinter;//当前打印机
        List<DigitalOutputBLL.STPrinter> ListPrinter;               //打印机集合
        MyControls.UserPrinter Printer;
        bool IsAutoDistribute = false;                              //是否是自动分配
        MyControls.UserPrinter AutoPrinter;                         //如果是自动分配，设置唯一的打印机
        List<int> DistributePhotoIds = new List<int>();             //待分配的照片Id集合

        //属性
        public bool DistributeMode { get; set; }                    //false按照片本身DPI分配 true按打印机DPI分配
        public bool CanContinue { get; set; }                       //是否继续  因为showdialog会死掉，换个方式 true继续，false停止
        public int AutoDistributePhotoNum { get; set; }             //每次自动分配的照片数
        public bool IsLX { get; set; }                              //是否连续按上次选择分配
        private int AotuCount = 0;
        private DataTable ErrTable=new DataTable();
        private bool StartAuto = false;
        public FrmDigitalMain2()
        {
            InitializeComponent();
            base.InitiAuthority();
            dgvPhotoList.ShowRowIndicator(50);
        }

        private void FrmDigitalMain2_Load(object sender, EventArgs e)
        {
            try
            {
                //CurrentTechId = 5;//测试使用3
                //base.userId = 5;
                //base.CurrentTechID = 5;
                spcPhoto.Panel2Collapsed = true;
                //获取当前节点Id
                CurrentTechId = base.CurrentTechID;
                //设置操作人员
                lblPeople.Text = base.userName;
                SetPrinterList(); //设置打印机
                tsPrinterList.SelectedIndexChanged -= tsPrinterList_SelectedIndexChanged;       //将打印机时间先取消
                tsPrinterList.Text = tsPrinterList.Items[0].ToString();
                foreach (BLL.DigitalOutput.DigitalOutputBLL.STPrinter pp in ListPrinter)
                {
                    if (pp.PrinterName == tsPrinterList.Text)
                    {
                        currentPrinter = pp;
                        break;
                    }
                }
                tscbIsDistributed.SelectedIndexChanged -= tscbIsDistributed_SelectedIndexChanged;
                tscbIsDistributed.Text = "未分配";
                tscbIsDistributed.SelectedIndexChanged += tscbIsDistributed_SelectedIndexChanged;
                //获取照片信息集合
                GetPhotoList(false, CurrentTechId);                  //未分配打印机的照片集合
                SetPhotoListDataSource(photoDT);                    //设置数据源
                //设置查询所需参数
                BindPaperType();    //纸型
                BindPaperFace();    //纸面
                BindShop();         //商户
                SetNum(photoDT);           //设置数量
                //spcPhoto2.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel2;
               // DBLL.DistributePrinter += new DigitalOutputBLL.ShowMessage(DBLL_DistributePrinter);

                tsPrinterList.SelectedIndexChanged += tsPrinterList_SelectedIndexChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 自动分配完成后返回的结果
        /// </summary>
        /// <param name="table"></param>
        /// <param name="disCount"></param>
        /// <returns></returns>
        void  DBLL_DistributePrinter(DataTable table, int disCount)
        {
            AotuCount += disCount;
            toolStripStatusLabelAuto.Text = "累计自动分配照片数：" + AotuCount + "出错数：" + table.Rows.Count;
            ErrTable = table;
        }

        #region 设置打印机
        /// <summary>
        /// 设置打印机
        /// </summary>
        private void SetPrinterList()
        {
            pPrinters.Controls.Clear();
            ListPrinter = DBLL.GetPrinterInfo();
            if (tsPrinterList.Items != null)
                tsPrinterList.Items.Clear();
            foreach (BLL.DigitalOutput.DigitalOutputBLL.STPrinter st in ListPrinter)
            {
                MyControls.UserPrinter userPrinter = new MINERP.DigitalOutput.MyControls.UserPrinter();
                //userPrinter.SetBaseInfo(st.PrinterID, st.PrinterName, st.PrinterType, st.PrinterDPI);
                userPrinter.SetBaseInfo(st.PrinterID, st.PrinterName, st.PrinterType, st.PrinterDPI, st.PrinterLength, st.PrinterWidth, st.Speed, st.IsDisable);
                userPrinter.SetTaskNum(st.TaskNum);
                userPrinter.Dock = DockStyle.Left;
                userPrinter.user_DragDrop += new DragEventHandler(userPrinter_user_DragDrop);
                userPrinter.user_DragEnter += new DragEventHandler(userPrinter_user_DragEnter);
                //userPrinter.user_DoubleClick += new MouseEventHandler(userPrinter_user_DoubleClick);
                //userPrinter.user_RightClick = new MINERP.DigitalOutput.MyControls.UserPrinter.DelRightClick(PrinterRightClick);
                pPrinters.Controls.Add(userPrinter);
                tsPrinterList.Items.Add(st.PrinterName);
                //自动分配目前不可用
                /*
                if (ListPrinter.Count == 1)
                {
                    tsAutoDistribute.Visible = true;
                    AutoPrinter = userPrinter;
                }*/
            }
        }


        #endregion

        #region 分配打印机
        /// <summary>
        /// 分配打印机
        /// </summary>
        /// <param name="photos">照片集合</param>
        private void DistributePrinter(List<MODEL.DigitalModel.STDistributePhoto> photos, MyControls.UserPrinter _printer)
        {
            int photoCount = dgvPhotoList.SelectedRowsCount;
            //没有照片被选中
            if (photoCount == 0)
            {
                return;
            }
            string _paperFace = "";
            foreach (MODEL.DigitalModel.STDistributePhoto p in photos)
            {
                if (p.PaperFace != "任意")
                {
                    _paperFace = p.PaperFace;
                    break;
                }
            }
            foreach (MODEL.DigitalModel.STDistributePhoto row in photos)
            {
                if (row.PaperFace == "任意")
                    continue;
                if (row.PaperFace != _paperFace)
                {
                    MessageBox.Show("相同的纸面才能分配同一台打印机!");
                    return;
                }
            }
            int PrinterDPI = _printer.PrinterDPI;
            DistributePrinterList(photos, _printer);
        }

        /// <summary>
        /// 分配选中的照片集合
        /// </summary>
        /// <param name="photos"></param>
        /// <param name="_printer"></param>
        private void DistributePrinterList(List<MODEL.DigitalModel.STDistributePhoto> photos, MyControls.UserPrinter _printer)
        {
            try
            {
                if (CurrentPhotoMode == false)                  //为照片分配打印机
                {
                    int photoNum = 0;
                    IsLX = false;                               //默认不连续分配
                    CanContinue = true;
                    foreach (MODEL.DigitalModel.STDistributePhoto photo in photos)
                    {
                        if (photo.PhotoDPI != _printer.PrinterDPI && IsLX == false)
                        {
                            FrmSetHWModel sm = new FrmSetHWModel();
                            sm.dm = this;
                            sm.PhotoCode = photo.PhotoCode;
                            sm.ShowDialog();
                        }
                        if (!CanContinue)
                            continue;
                        int num = 0;
                        if (photo.PhotoDPI != _printer.PrinterDPI && DistributeMode)                  //按打印机DPI计算尺寸
                        {
                            photo.DistributeType = true;
                        }
                        else 
                        {
                            photo.DistributeType = false;
                        }
                        num = DBLL.DistributeSinglePhoto(photo, _printer.PrinterDPI, CurrentTechId, userId);   //返回总共分配的数量
                        //num = DBLL.DistributeSinglePhotoTradition(photo, _printer.PrinterDPI, CurrentTechId, userId);   //返回总共分配的数量
                        photoNum += num;

                    }
                    dgvPhotoList.ClearSelection();
                    //刷新任务量
                    _printer.SetTaskNum(photoNum);
                    SetIsDistributed(tscbIsDistributed.Text);
                }
                else if (CurrentPhotoMode == true)      //为照片更改打印机
                {
                    IsLX = false;
                    CanContinue = true;
                    int photoNum = 0;
                    foreach (MODEL.DigitalModel.STDistributePhoto photo in photos)
                    {
                        if (photo.PhotoDPI != _printer.PrinterDPI && IsLX == false)
                        {
                            FrmSetHWModel sm = new FrmSetHWModel();
                            sm.dm = this;
                            sm.PhotoCode = photo.PhotoCode;
                            sm.ShowDialog();
                        }
                        if (!CanContinue)
                        {
                            continue;
                        }
                        photo.PrinterID = _printer.PrinterID;
                        if (photo.PhotoDPI != _printer.PrinterDPI && DistributeMode)
                        {
                            photo.DistributeType = true;
                        }
                        else
                        {
                            photo.DistributeType = false;
                        }
                        DBLL.ChangePrinterDPISingle(photo, _printer.PrinterDPI);
                        photoNum++;
                    }
                    //DBLL.ChangePrinterForPhoto(photos, CurrentTechId, currentPrinter.PrinterID, _printer.PrinterID);
                    SetIsDistributed(tscbIsDistributed.Text);
                    dgvPhotoList.ClearSelection();
                    int num = photoNum;

                    foreach (Control c in pPrinters.Controls)
                    {
                        MyControls.UserPrinter up = c as MyControls.UserPrinter;
                        if (up != null && up.PrinterID == currentPrinter.PrinterID)
                        {
                            //减少
                            up.SetTaskNum(-num);
                            //增加
                            _printer.SetTaskNum(num);
                            break;
                        }
                    }
                }
                if (IsFind == true)                     //处于查询模式
                {
                    btnFind_Click(new object(), new EventArgs());
                }
                SetNum(photoDT);                       //设置数量
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 自动分配
        /// </summary>
        public int AutoDistributePrinter()
        {
            if (dgvPhotoList.RowCount == 0)
                return 0;
            List<MODEL.DigitalModel.STDistributePhoto> photos = new List<MODEL.DigitalModel.STDistributePhoto>();
            int PrinterDPI = currentPrinter.PrinterDPI;             //打印机的DPI
            int printerID = currentPrinter.PrinterID;
            int photoNum = 0;
            for (int i = 0; i < dgvPhotoList.RowCount; i++)         //设置待分配照片的集合
            {
                DataRow row = dgvPhotoList.GetDataRow(i);
                int photoId = Convert.ToInt32(row["PhotoID"]);
                bool isSizeMatch = DBLL.CheckPicSize(photoId);
                if (isSizeMatch == false)                           //照片本身尺寸与本身尺寸不匹配
                {
                    continue;
                }
                
                MODEL.DigitalModel.STDistributePhoto photo = new MODEL.DigitalModel.STDistributePhoto();
                if (photo.PrinterID == 0)
                {
                    if (Convert.ToInt32(row["PhotoDPI"]) != PrinterDPI) //分辨率不等执行下一条
                    { continue; }
                    photo.PrinterID = printerID;//只分未指定打印机的
                    photo.PhotoID = photoId;

                    photo.Status = Convert.ToInt16((int)COM.PhotoStatus.DistributedPrinter);
                    photo.DistributeType = false;                       //默认按照片DPI分配
                    photoNum += DBLL.DistributeSinglePhoto(photo, currentPrinter.PrinterDPI, CurrentTechId, userId);
                }
                else
                {
                 
                    MINERP.BLL.DigitalOutput.DigitalOutputBLL.STPrinter printer = DBLL.GetPrinter(photo.PrinterID);
                    if (Convert.ToInt32(row["PhotoDPI"]) != printer.PrinterDPI) //分辨率不等执行下一条
                    { continue; }
                    photo.PhotoID = photoId;

                    photo.Status = Convert.ToInt16((int)COM.PhotoStatus.DistributedPrinter);
                    photo.DistributeType = false;                       //默认按照片DPI分配
                    photoNum += DBLL.DistributeSinglePhoto(photo, printer.PrinterDPI, CurrentTechId, userId);
                }
                
            }
            //刷新任务量
            AutoPrinter.SetTaskNum(photoNum);
            SetIsDistributed(tscbIsDistributed.Text);
            SetNum(photoDT);
            return photoNum;
        }
        #endregion

        private void ChangePrinter(List<MODEL.DigitalModel.STDistributePhoto> photos, MyControls.UserPrinter _printer)
        {

        }

        /// <summary>
        /// 获取用户控件
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private void GetPrinter(object sender)
        {
            Control control = sender as Control;
            if (control as MyControls.UserPrinter == null)
                GetPrinter(control.Parent);
            else
                Printer = sender as MyControls.UserPrinter;
        }

        /// <summary>设置照片信息集合
        /// 设置照片信息集合
        /// </summary>
        private void GetPhotoList(bool IsDistributed, int techId)
        {
            List<string> ErrList=new List<string>();
            DataTable allPhoto = DBLL.GetPhotoList(IsDistributed, techId, currentPrinter.PrinterID, out ErrList);
            if (ErrList != null && ErrList.Count!=0)
            {
                string errString = "";
                foreach (string s in ErrList)
                {
                    errString += s;
                }
                MessageBox.Show("以下照片尺寸为0请确认！[格式(产品号，照片号)]"+errString, "确定", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }          
            //将已预先分配了打印机的照片自动分配打印机
            if (IsDistributed == false)             //未分配  
            {
                DataTable preDistributePrinterDt = allPhoto.Clone();
                DataRow[] preRows = allPhoto.Select("printerId<>0");        //printerId!=0表示已预先分配了打印机
                foreach (DataRow r in preRows)
                {
                    DataRow nr = preDistributePrinterDt.NewRow();
                    nr.ItemArray = r.ItemArray;
                    preDistributePrinterDt.Rows.Add(nr);
                }
                //自动预分配
                PreDistributePhoto(preDistributePrinterDt);

                DataRow[] noPreRows = allPhoto.Select("printerId=0");       //printerId=0表示需要手动分配
                photoDT = allPhoto.Clone();
                foreach (DataRow r in noPreRows)
                {
                    DataRow nr = photoDT.NewRow();
                    nr.ItemArray = r.ItemArray;
                    photoDT.Rows.Add(nr);
                }
            }
            else                                    //已分配
            {
                photoDT = allPhoto;
            }
        }

        /// <summary>
        /// 有预分配的照片自动进行预分配
        /// </summary>
        /// <param name="preDt"></param>
        private void PreDistributePhoto(DataTable preDt)
        {
            int photoid = 0;
            try
            {
                if (preDt == null || preDt.Rows.Count == 0)
                    return;
                List<MODEL.DigitalModel.STDistributePhoto> photos = new List<STDistributePhoto>();
                foreach (DataRow r in preDt.Rows)
                {
                    MODEL.DigitalModel.STDistributePhoto photo = new MODEL.DigitalModel.STDistributePhoto();
                    photoid = Convert.ToInt32(r["PhotoID"]);
                    photo.PhotoID = Convert.ToInt32(r["PhotoID"]);
                    photo.PhotoCode = r["PhotoBarCode"].ToString();
                    photo.Status = (int)MINERP.COM.PhotoStatus.DistributedPrinter;
                    photo.PhotoDPI = Convert.ToInt32(r["PhotoDPI"]);
                    int printerId = Convert.ToInt32(r["PrinterId"]);
                    int printerDpi = 0;
                    foreach (DigitalOutputBLL.STPrinter printer in ListPrinter)
                    {
                        if (printerId == printer.PrinterID)
                        {
                            printerDpi = printer.PrinterDPI;
                        }
                    }
                    photo.PrinterDPI = printerDpi;                      //将打印机DPI记录下来，在预分配时使用
                    photo.PrinterID = printerId;
                    if (photo.PhotoDPI != printerDpi)                   //照片DPI不等于打印机DPI，按照片本身尺寸分配
                    {
                        photo.DistributeType = false;
                    }
                    photo.PaperFace = r["PaperFaceName"].ToString();
                    photo.OrderProductID = Convert.ToInt32(r["OrderProductID"]);
                    string[] photoSizes = r["PhotoSize"].ToString().Split('×');
                    photo.Width = Convert.ToDouble(photoSizes[0]);
                    photo.Height = Convert.ToDouble(photoSizes[1]);
                    photo.OrderPriority = Convert.ToInt16(r["OrderPriority"]);
                    photos.Add(photo);
                }
                int num = 0;
                foreach (MODEL.DigitalModel.STDistributePhoto photo in photos)
                {
                    num += DBLL.DistributeSinglePhoto(photo, photo.PrinterDPI, CurrentTechId, userId);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                throw new Exception("照片号" + photoid + "出现异常，异常为：" + ex.Message);
            }
        }

        /// <summary>设置照片列表的数据源
        /// 设置照片列表的数据源
        /// </summary>
        public void SetPhotoListDataSource(DataTable dt)
        {
            gcPhotoList.DataSource = dt;
            gcPhotoList.RefreshDataSource();
        }

        bool IsZK = true;      //false收缩 true展开
        //展开
        private void ZhanKai()
        {
            AcceptButton = null;
            AcceptButton = btnFind;
            CancelButton = null;
            CancelButton = btnReset;
            spcPhoto.Panel2Collapsed = false;
            IsZK = true;
        }
        //收缩
        private void ShouSuo()
        {
            spcPhoto.Panel2Collapsed = true;
            IsZK = false;
        }
        //展开"查询"
        private void tsFind_Click(object sender, EventArgs e)
        {
            try
            {
                ZhanKai();
                tcFindAndOrder.SelectedTab = tpFind;
                IsFind = true;  //表示正处于查询模式
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //展开"订单"
        private void tsOrderInfo_Click(object sender, EventArgs e)
        {
            try
            {
                ZhanKai();
                tcFindAndOrder.SelectedTab = tpOrder;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //"关闭"按钮
        private void tsCloseRight_Click(object sender, EventArgs e)
        {
            try
            {
                ShouSuo();
                IsFind = false; //如果原来处于查询模式下,在关闭查询窗口时,需取消查询模式
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //刷新按钮
        private void tsRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ttRefresh.Stop();
                ttRefresh.Start();
                //设置打印机
                SetPrinterList();
                //加载未分配打印机的照片列表
                SetIsDistributed(tscbIsDistributed.Text);
                SetNum(photoDT);
                Cursor = Cursors.Default;
                IsFind = false; //取消查询模式
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region 绑定纸型
        /// <summary>
        /// 绑定纸型
        /// </summary>
        private void BindPaperType()
        {
            List<string> listPaperType = DBLL.GetPaperType();
            txtPaperType.Items.Add("全选");
            foreach (string s in listPaperType)
            {
                txtPaperType.Items.Add(s);
            }
            txtPaperType.Text = "全选";
        }
        #endregion 绑定纸型

        #region 绑定纸面
        /// <summary>
        /// 绑定纸面
        /// </summary>
        private void BindPaperFace()
        {
            List<string> listPaperFace = DBLL.GetPaperFace();
            txtPaperFace.Items.Add("全选");
            foreach (string s in listPaperFace)
            {
                txtPaperFace.Items.Add(s);
            }
            txtPaperFace.Text = "全选";
        }
        #endregion 绑定纸型

        #region 绑定商户
        /// <summary>
        /// 绑定商户
        /// </summary>
        private void BindShop()
        {
            DataTable DTShop = DBLL.GetShop();
            txtShopName.DisplayMember = "ShopName";
            txtShopName.ValueMember = "ShopID";
            txtShopName.DataSource = DTShop;
        }
        #endregion

        #region 查询操作
        bool IsFind = false;    //当前是否正处于查询模式下
        //查询操作
        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                IsFind = true;
                string findPaperType = txtPaperType.Text.Trim();
                if (findPaperType == "全选")
                    findPaperType = "";
                string findPaperFace = txtPaperFace.Text.Trim();
                if (findPaperFace == "全选")
                    findPaperFace = "";
                string findShopName = txtShopName.Text.Trim();
                if (findShopName == "全选")
                    findShopName = "";
                string findCtmName = txtCtmName.Text.Trim();
                string findOrderBarCode = txtOrderBarCode.Text.Trim();
                string findOrderDetailBarCode = txtOrderDetailBarCode.Text.Trim();
                string findPhotoBarCode = txtPhotoBarCode.Text.Trim();
                filterPhotoDT = DBLL.GetFilterPhotoDT(photoDT, findPaperType, findPaperFace, findShopName, findCtmName, findOrderBarCode, findOrderDetailBarCode, findPhotoBarCode);
                SetPhotoListDataSource(filterPhotoDT);
                SetNum(filterPhotoDT);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 清除所有的查询条件
        //清除所有的查询条件
        private void btnReset_Click(object sender, EventArgs e)
        {
            txtPaperType.Text = "";
            txtPaperFace.Text = "";
            txtShopName.Text = "";
            txtCtmName.Text = "";
            txtOrderBarCode.Text = "";
            txtOrderDetailBarCode.Text = "";
            txtPhotoBarCode.Text = "";
        }
        #endregion

        #region 固定的时间,刷新数据源
        //固定的时间,刷新数据源
        private void timer1_Tick(object sender, EventArgs e)
        {

        }
        #endregion

        #region 设置查询界面按钮的快捷键
        //设置查询界面展开的快捷键
        private void FrmDigitalMain_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control && e.KeyCode == Keys.F)     //展开"查询"
                {
                    tsFind_Click(sender, e);
                }
                else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)//关闭
                {
                    tsCloseRight_Click(sender, e);
                }
                else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.R)//刷新
                {
                    tsRefresh_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 设置照片数量，产品数量，订单数量
        /// <summary>
        /// 设置照片数量，产品数量，订单数量
        /// </summary>
        private void SetNum(DataTable dt)
        {
            int photoNum = dt.Rows.Count;
            decimal photoSAreas = 0;
            
            List<int> lists = new List<int>();
            DataTable DTProduct = dt.Clone();
            DataTable DTOrder = dt.Clone();
            foreach (DataRow r in dt.Rows)
            {
                DataRow nr1 = DTProduct.NewRow();
                DataRow nr2 = DTOrder.NewRow();
                nr1.ItemArray = r.ItemArray;
                nr2.ItemArray = r.ItemArray;
                DTProduct.Rows.Add(nr1);
                DTOrder.Rows.Add(nr2);
                photoSAreas += Convert.ToDecimal(r["PhotoAreas"]);
            }
            DataView dv = DTProduct.DefaultView;
            DataTable DTProductDistinct = dv.ToTable(true, "OrderProductID");
            int productNum = DTProductDistinct.Rows.Count;
            DataView dv2 = DTOrder.DefaultView;
            DataTable DTOrderDistinct = dv2.ToTable(true, "OrderBagID");
            int orderNum = DTOrderDistinct.Rows.Count;
            lblPhotoNum.Text = photoNum.ToString();
            lblProductNum.Text = productNum.ToString();
            lblOrderNum.Text = orderNum.ToString();
            labelControlAresa.Text = photoSAreas.ToString("0.00")+"㎡";
            
        }
        #endregion

        #region 当订单信息是展开的时，点击列表显示该行的订单信息
        private void dgvPhotoList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {

        }

        private void dgvPhotoList_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                //if (spcPhoto2.PanelVisibility == DevExpress.XtraEditors.SplitPanelVisibility.Both && tcFindAndOrder.SelectedTab == tpOrder)
                if (spcPhoto.Panel2Collapsed == false && tcFindAndOrder.SelectedTab == tpOrder)
                {
                    int rowHandle = e.RowHandle;
                    if (rowHandle < 0)             //组行
                    {
                        string colCaption = dgvPhotoList.GetGroupRowDisplayText(rowHandle).Split(':')[0];
                        string colValue = dgvPhotoList.GetGroupRowValue(rowHandle).ToString();

                        foreach (DevExpress.XtraGrid.Columns.GridColumn col in dgvPhotoList.Columns)
                        {
                            if (col.Caption == colCaption)
                            {
                                string filterStr = col.FieldName + "=" + colValue;
                                DataRow[] rows = photoDT.Select(filterStr);
                                if (rows.Length > 0)
                                {
                                    int orderBagID = Convert.ToInt32(rows[0]["OrderBagID"]);
                                    SetOrderInfo(orderBagID);
                                }
                                return;
                            }
                        }
                    }
                    else                            //普通行
                    {
                        DataRow row = dgvPhotoList.GetDataRow(rowHandle);
                        int orderBagId = Convert.ToInt32(row["OrderBagID"]);
                        SetOrderInfo(orderBagId);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 设置订单信息
        /// <summary>
        /// 设置订单信息
        /// </summary>
        /// <param name="orderBagId"></param>
        private void SetOrderInfo(int orderBagId)
        {
            DigitalOutputBLL.CSOrderInfo orderInfo = DBLL.GetOrderInfoByOrderId(orderBagId);
            txtOrderBagCode.Text = orderInfo.OrderBagCode;
            txtOrderName.Text = orderInfo.OrderName;
            txtShopName2.Text = orderInfo.ShopName;
            txtPriority.Text = orderInfo.OrderPriority.ToString();
            txtOrderTime2.Text = orderInfo.OrderTime.ToString("yyyy年MM月dd日 HH时mm分");
            txtPreFetchTime.Text = orderInfo.PreCompleteTime.ToString("yyyy年MM月dd日 HH时mm分");
            txtShopRequire.Text = orderInfo.OrderRemark;
        }
        #endregion

        //-------------------------------------
        //----------拖曳分配打印机-------------
        //-------------------------------------

        GridHitInfo downHitInfo = null;
        private void dgvPhotoList_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                GridHitInfo info = view.CalcHitInfo(new Point(e.X, e.Y));
                if (e.Button == MouseButtons.Left && info.InRow && info.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = info;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgvPhotoList_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    List<MODEL.DigitalModel.STDistributePhoto> photos = new List<MODEL.DigitalModel.STDistributePhoto>();                             //要分配的照片ID集合
                    if (!rec.Contains(e.X, e.Y))
                    {
                        Cursor = Cursors.IBeam;
                        DistributePhotoIds.Clear();
                        int[] indexes = dgvPhotoList.GetSelectedRows();
                        GetDragData(view, photos);
                        downHitInfo = null;
                        CurrentPhotoMode = true;//不控制加急基本
                        if (CurrentPhotoMode == false)                      //分配打印机，需要判断加急级别；修改不需要判断加急级别
                        {
                            //判断选中照片的加急级别是否相等，若相等是否是最大的
                            int priority = Convert.ToInt32(photos[0].OrderPriority);
                            bool isEqual = true;
                            foreach (MODEL.DigitalModel.STDistributePhoto p in photos)
                            {
                                if (p.OrderPriority != priority)
                                {
                                    isEqual = false;
                                    break;
                                }
                            }
                            if (isEqual == false)
                            {
                                Cursor = Cursors.Default;
                                MessageBox.Show("同时分配的照片加急级别必须相等！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                            //是否是最大的
                            bool isBigest = true;
                            foreach (DataRow r in photoDT.Rows)
                            {
                                if (Convert.ToInt32(r["OrderPriority"]) > priority)
                                {
                                    isBigest = false;
                                    break;
                                }
                            }
                            if (isBigest == false)
                            {
                                Cursor = Cursors.Default;
                                MessageBox.Show("选中的照片加急级别不是最大的！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                        }
                        DataObject data = new DataObject();
                        data.SetData("list", photos);
                        DoDragDrop(data, DragDropEffects.All);
                        Cursor = Cursors.Default;
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message);
            }
        }
        //获取分组的照片
        private void GetDragData(GridView view, List<MODEL.DigitalModel.STDistributePhoto> photos)
        {
            ArrayList result = new ArrayList();
            int[] selection = view.GetSelectedRows();

            DataRowView row = (DataRowView)view.GetFocusedRow();
            if (selection == null) return;
            int count = selection.Length;


            GridColumnReadOnlyCollection columns = view.GroupedColumns;

            for (int i = 0; i < count; i++)
            {
                if (view.IsGroupRow(selection[i]))
                {
                    string endPiont = view.GetGroupRowDisplayText(selection[i]).Split(':')[0];
                    int intEndPiont = 0;
                    for (int j = 0; j < columns.Count; j++)
                    {
                        if (endPiont.Equals(columns[j].Caption))
                        {
                            intEndPiont = j;
                            break;
                        }
                    }
                    List<string> arrColName = new List<string>();
                    for (int j = intEndPiont; j >= 0; j--)
                    {
                        arrColName.Add(columns[j].FieldName);
                    }


                    Hashtable hashtable = new Hashtable();
                    int intSkip = 0;
                    Hashtable check = new Hashtable();
                    for (int m = 0; m <= intEndPiont; m++)
                    {
                        string checkstr = view.GetGroupRowDisplayText(selection[i] + intSkip + m).Split(':')[0];
                        string oo = view.GetGroupRowValue(selection[i] + intSkip + m).ToString();
                        if (check.Contains(checkstr))
                        {
                            intSkip++;
                            m--;
                            continue;
                        }
                        var pp = arrColName[m].ToString();
                        hashtable.Add(pp, oo);
                        check.Add(checkstr, m);
                    }
                    string selectStr = "1=1";
                    foreach (DictionaryEntry hash in hashtable)
                    {
                        selectStr += " and " + hash.Key + "='" + hash.Value + "'";
                    }
                    DataRow[] rows = photoDT.Select(selectStr);
                    foreach (DataRow r in rows)
                    {
                        int pid = Convert.ToInt32(r["PhotoID"]);
                        if (DistributePhotoIds.Contains(pid))
                            continue;
                        DistributePhotoIds.Add(pid);
                        MODEL.DigitalModel.STDistributePhoto photo = new MODEL.DigitalModel.STDistributePhoto();
                        photo.PhotoID = pid;
                        photo.PhotoCode = r["PhotoBarCode"].ToString();
                        photo.Status = (int)MINERP.COM.PhotoStatus.DistributedPrinter;
                        photo.PhotoDPI = Convert.ToInt32(r["PhotoDPI"]);
                        photo.PaperFace = r["PaperFaceName"].ToString();
                        photo.OrderProductID = Convert.ToInt32(r["OrderProductID"]);
                        string[] photoSizes = r["PhotoSize"].ToString().Split('×');
                        photo.Width = Convert.ToDouble(photoSizes[0]);
                        photo.Height = Convert.ToDouble(photoSizes[1]);
                        photo.OrderPriority = Convert.ToInt16(r["OrderPriority"]);
                        photos.Add(photo);
                    }
                }
                else
                {
                    DataRow r = view.GetDataRow(selection[i]);
                    int pid = Convert.ToInt32(r["PhotoID"]);
                    if (DistributePhotoIds.Contains(pid))
                        continue;
                    DistributePhotoIds.Add(pid);
                    MODEL.DigitalModel.STDistributePhoto photo = new MODEL.DigitalModel.STDistributePhoto();
                    photo.PhotoID = pid;
                    photo.PhotoCode = r["PhotoBarCode"].ToString();
                    photo.Status = (int)MINERP.COM.PhotoStatus.DistributedPrinter;
                    photo.PhotoDPI = Convert.ToInt32(r["PhotoDPI"]);
                    photo.PaperFace = r["PaperFaceName"].ToString();
                    photo.OrderProductID = Convert.ToInt32(r["OrderProductID"]);
                    string[] photoSizes = r["PhotoSize"].ToString().Split('×');
                    photo.Width = Convert.ToDouble(photoSizes[0]);
                    photo.Height = Convert.ToDouble(photoSizes[1]);
                    photo.OrderPriority = Convert.ToInt16(r["OrderPriority"]);
                    photos.Add(photo);
                }
            }
        }

        #region 拖曳分配打印机
        void userPrinter_user_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent("list"))
                {
                    e.Effect = DragDropEffects.All;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void userPrinter_user_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent("list"))
                {
                    //获取当前被选中的打印机
                    GetPrinter(sender);
                    MyControls.UserPrinter _printer = Printer;
                    List<MODEL.DigitalModel.STDistributePhoto> photos = e.Data.GetData("list") as List<MODEL.DigitalModel.STDistributePhoto>;
                    List<MODEL.DigitalModel.STDistributePhoto> matchPhotos = new List<STDistributePhoto>();     //高宽符合的照片
                    bool isHWNoMatch = false;
                    foreach (MODEL.DigitalModel.STDistributePhoto p in photos)
                    {
                        if (p.Width > _printer.PrinterLength || p.Height > _printer.Width)
                        {
                            isHWNoMatch = true;             //照片高宽已超过打印机范围，不能分配
                            continue;
                        }
                        else
                        {
                            p.PrinterID = _printer.PrinterID;
                            matchPhotos.Add(p);
                        }
                    }
                    //DistributePrinter(photos, _printer);
                    DistributePrinter(matchPhotos, _printer);
                    if (isHWNoMatch)
                    {
                        MessageBox.Show("有部分照片尺寸已超过打印机范围，不能分配，请检查！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        

        //未分配还是已分配打印机
        private void tscbIsDistributed_SelectedIndexChanged(object sender, EventArgs e)
        {
            string statusStr = tscbIsDistributed.Text;
            SetIsDistributed(statusStr);
            SetNum(photoDT);
        }
        /// <summary>
        /// 分配(未分配)打印机
        /// </summary>
        /// <param name="statusStr"></param>
        private void SetIsDistributed(string statusStr)
        {
            if (statusStr == "已分配")
            {
                CurrentPhotoMode = true;
                tsPrinterList.Visible = true;
                GetPhotoList(true, CurrentTechId);
                SetPhotoListDataSource(photoDT);
            }
            else if (statusStr == "未分配")
            {
                CurrentPhotoMode = false;
                tsPrinterList.Visible = false;
                GetPhotoList(false, CurrentTechId);
                SetPhotoListDataSource(photoDT);
            }
        }

        #region 设置已分配照片的当前打印机
        /// <summary>
        /// 已分配照片的当前打印机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsPrinterList_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (DigitalOutputBLL.STPrinter p in ListPrinter)
            {
                if (tsPrinterList.Text == p.PrinterName)
                {
                    currentPrinter = p;
                    GetPhotoList(true, p.PrinterID);
                    SetPhotoListDataSource(photoDT);
                    SetNum(photoDT);
                    break;
                }
            }
        }
        #endregion

        /// <summary>
        /// 设置已分配打印机照片源
        /// </summary>
        private void SetDistributedDT()
        {
            List<string>ErrList=new List<string>();
            DBLL.GetPhotoList(true, currentPrinter.PrinterID, currentPrinter.PrinterID,out  ErrList);
            //if (ErrList != null || ErrList.Count != 0)
            //{
            //    string errString = "";
            //    foreach (string s in ErrList)
            //    {
            //        errString += s;
            //    }
            //    MessageBox.Show("以下照片尺寸为0请确认！[格式(产品号，照片号)]+errString", "确定", MessageBoxButtons.OK, MessageBoxIcon.Information);

            //}          
        }

        private void FrmDigitalMain2_FormClosing(object sender, FormClosingEventArgs e)
        {
            COM.Logoff.ShowMainFrm();
        }

        private void tsExit_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("确定要退出吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                this.Close();
            }
        }

        /*
        //如果只有一台打印机，自动分配
        public void tsAutoDistribute_Click(object sender, EventArgs e)
        {
            if (IsAutoDistribute == false)                              //当前是手动分配
            {
                IsAutoDistribute = true;
                ttRefresh.Enabled = false;
                tsAutoDistribute.Text = "手动分配";
                FrmAutoDistributeRunning fad = new FrmAutoDistributeRunning();
                fad.fdm = this;
                fad.ShowDialog();
            }
            else                                                        //当前是自动分配
            {
                IsAutoDistribute = false;
                tsAutoDistribute.Text = "自动分配";
            }
        }*/

        public void ttRefresh_Tick(object sender, EventArgs e)
        {
            try
            {
                if (IsAutoDistribute == true)                           //自动分配
                {
                    GetPhotoList(false, CurrentTechId);
                    SetPhotoListDataSource(photoDT);
                    //执行自动分配任务
                    tscbIsDistributed.Text = "未分配";
                    int photoNum = AutoDistributePrinter();
                    AutoDistributePhotoNum = photoNum;
                }
                else                                                    //手动分配
                {
                    if (IsFind == true) //处于查询模式
                    {
                        btnFind_Click(new object(), e);

                    }
                    else
                    {
                        SetIsDistributed(tscbIsDistributed.Text);
                        SetNum(photoDT);
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        //行背景色 0-5正常；6-10：粉红；11：红色
        private void dgvPhotoList_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle >= 0)
                {
                    DataRow row = dgvPhotoList.GetDataRow(e.RowHandle);
                    /*
                    int back = (int)COM.OrderBagType.Reback;
                    if (Convert.ToInt16(row["OrderProductType"]) == back)
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                    else
                    {
                        e.Appearance.BackColor = Color.Empty;
                        e.Appearance.BackColor2 = Color.Empty;
                    }*/
                    int priority = Convert.ToInt32(row["OrderPriority"]);
                    if (priority < 6)
                    {
                        e.Appearance.BackColor = Color.Empty;
                        e.Appearance.BackColor2 = Color.Empty;
                    }
                    else if (priority >= 6 && priority <= 10)
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                    else if (priority == 11)
                    {
                        e.Appearance.BackColor = Color.Red;
                        e.Appearance.BackColor2 = Color.Red;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //----------------------------------------------------------------------------
        //--------------------------自动分配------------------------------------------
        #region 自动分配按钮
        public void tsAutoDistribute_Click(object sender, EventArgs e)
        {
            try
            { 
                //检查是否有速度不匹配的打印机
                foreach (Control pp in pPrinters.Controls)
                {
                    MyControls.UserPrinter p = pp as MyControls.UserPrinter;
                    if (p.Speed <= 0)
                    {
                        MessageBox.Show("存在打印速度不正确的打印机，请先设置打印机属性", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                AutoDistribute.FrmAuto frm = new MINERP.DigitalOutput.AutoDistribute.FrmAuto();
                frm.frm = this;
                frm.CurrentTechId = CurrentTechId;
                frm.ListPrinter = ListPrinter.Where(p => p.IsDisable == true).ToList();
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 各种事件、委托
        //双击修改打印机属性
        void userPrinter_user_DoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {
                    //弹出修改打印机属性对话框
                    MyControls.UserPrinter p = (MyControls.UserPrinter)sender;
                    AutoDistribute.FrmPrinterAttribute frm = new MINERP.DigitalOutput.AutoDistribute.FrmPrinterAttribute();
                    frm.StartPosition = FormStartPosition.CenterScreen;
                    frm.Frm = this;
                    frm.Printer = p;
                    frm.SetOldAttribute(p);
                    frm.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //右击修改打印机属性
        private void PrinterRightClick(Control sender)
        {
            try
            {
                //弹出修改打印机属性对话框
                MyControls.UserPrinter p = (MyControls.UserPrinter)sender;
                AutoDistribute.FrmPrinterAttribute frm = new MINERP.DigitalOutput.AutoDistribute.FrmPrinterAttribute();
                frm.Printer = p;
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.Frm = this;
                frm.SetOldAttribute(p);
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        /// <summary>
        /// 设置打印机属性
        /// </summary>
        public void SetPrinterAttribute(MyControls.UserPrinter printer)
        {
            DBLL.SetPrinterAttribute(printer.PrinterID, printer.PrinterLength, printer.Width, printer.Speed, printer.PrinterDPI, printer.IsDisable);
            DigitalOutputBLL.STPrinter p = ListPrinter.Where(pp => pp.PrinterID == printer.PrinterID).First();
            p.PrinterLength = printer.PrinterLength;
            p.PrinterWidth = printer.PrinterWidth;
            p.Speed = printer.Speed;
            p.PrinterDPI = printer.PrinterDPI;
            p.IsDisable = printer.IsDisable;
            printer.SetBaseInfo(printer.PrinterID, printer.PrinterName, "1", printer.PrinterDPI);
        }
       
        private void toolStripButtonAutoDistri_Click(object sender, EventArgs e)
        {
            //if (StartAuto)
            //{
            //    StartAuto = false;
            //    toolStripButtonAutoDistri.Text = "开启自动分配";
               
            //    DBLL.EndAutoDistribute();
            //}
            //else
            //{
            //    List<string> listPrinter = DBLL.CheckPrinter();
            //    if (listPrinter.Count==0)
            //    {
            //        StartAuto = true;
            //        toolStripButtonAutoDistri.Text = "关闭自动分配";
            //        DBLL.StartAutoDistribute(CurrentTechID, userId);
            //    }
            //    else
            //    {
            //        string ErrPrinterName = "";
            //        foreach (string p in listPrinter)
            //        {
            //            ErrPrinterName = ErrPrinterName + p + ",";
            //        }
            //        MessageBox.Show(ErrPrinterName+" 以上打印机的打印范围为指定！请在后台设定", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}

            FrmAutoAssion frm = new FrmAutoAssion(CurrentTechId, userId);
            frm.ShowDialog();
            tsRefresh_Click(null,null);

        }

       

        private void toolStripButtonCheckErr_Click(object sender, EventArgs e)
        {
            FrmAutoDistriErr frmAutoDistriErr = new FrmAutoDistriErr(ErrTable);
            frmAutoDistriErr.Show();
        }

        private void dgvPhotoList_Click(object sender, EventArgs e)
        {
            int[] selectRowids = dgvPhotoList.GetSelectedRows();
            //DataRow r = view.GetDataRow(selection[i]);
            decimal selectAreas = 0;
            foreach (int rowid in selectRowids)
            {
                DataRow r = dgvPhotoList.GetDataRow(rowid);
                selectAreas += Convert.ToDecimal(r["PhotoAreas"]);
            }
            labelControl2.Text = selectAreas.ToString("0.00");
        }

    }
}
